package com.shop.wk.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author 日月星辰
 * @date 2020/12/26 20:27
 * @description
 */
@Configuration
public class RedisConfig {

  @Bean
  @ConditionalOnMissingBean(name = "redisTemplate")
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
    StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    GenericJackson2JsonRedisSerializer JACKSON__SERIALIZER = new GenericJackson2JsonRedisSerializer();
    // 配置redisTemplate
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setConnectionFactory(factory);
    // key序列化
    redisTemplate.setKeySerializer(STRING_SERIALIZER);
    // value序列化
    redisTemplate.setValueSerializer(JACKSON__SERIALIZER);
    // Hash key序列化
    redisTemplate.setHashKeySerializer(STRING_SERIALIZER);
    // Hash value序列化
    redisTemplate.setHashValueSerializer(JACKSON__SERIALIZER);
    redisTemplate.afterPropertiesSet();
    return redisTemplate;
  }
}
